<script setup>

import { useForgotState } from '@/stores/index.js'
import { ref } from 'vue'
import { successMsg } from '@/utils/sendMsgUtils.js'
import { changePasswordService } from '@/api/user.js'
import { encryption } from '@/utils/md5Utils.js'
import { useRouter } from 'vue-router'


const router = useRouter()
const forgotState = useForgotState()

const rules = ref({
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  tPassword: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        try {
          if (value === forgotState.fUser.password) {
            callback()
          } else {
            callback(new Error('密码不一致'))
          }
        } catch {
          callback(new Error('密码不一致'))
        }
      },
      trigger: 'blur'
    }
  ],
})

const changePassword = async () => {
  forgotState.fUser.password = encryption(forgotState.fUser.password)
  const resp = await changePasswordService(forgotState.fUser)
  if (resp.code === 1) {
    successMsg(resp.data)
    await router.push('/user/login')
  }
}
</script>

<template>
  <el-form
    :model="forgotState.fUser"
    :rules="rules"
    ref="formRef"
    style="max-width: 320px"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="新密码：" prop="password">
      <el-input type="password" style="width: 300px" v-model="forgotState.fUser.password" />
    </el-form-item>
    <el-form-item label="确认密码：" prop="tPassword">
      <el-input type="password" style="width: 300px" v-model="forgotState.fUser.tPassword" />
    </el-form-item>
    <div style=" text-align: center;margin-bottom: 15px">
      <el-button style="width: 250px" size="large" round type="primary" @click="changePassword ">
        更改密码
      </el-button>
    </div>
  </el-form>
</template>

<style scoped>

</style>
